package com.xzhuang.task.quartz;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import net.sf.json.JSONObject;

import org.apache.commons.collections.map.HashedMap;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.xzhuang.task.util.DBUtil;
import com.xzhuang.task.util.HttpUtil;
import com.xzhuang.task.util.HttpUtilX;
import com.xzhuang.task.util.QuartzUtil;

/**
 * 
 * @Description: 若一个方法一次执行不完下次轮转时则等待改方法执行完后才执行下一次操作
 */

@DisallowConcurrentExecution
public class QuartzJobFactoryDisallowConcurrentExecution implements Job {
	// public final Logger log = Logger.getLogger(this.getClass());

	String desc = "";
	String[] param;

	public void execute(JobExecutionContext context) throws JobExecutionException {
		// QuartzUtil.invokMethod(scheduleJob);
		DBUtil db = new DBUtil();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		ScheduleTask task = (ScheduleTask) context.getMergedJobDataMap().get("scheduleJob");
		String json = null;
		String str = "";
		try {
			desc = task.getDescription();
			param = QuartzUtil.getExtendParam(desc);
			if (param[0].equals("1")) {// GET
//				json = HttpUtil.GET(task.getJobName());
				json = HttpUtilX.get(task.getJobName());
			} else {
//				json = HttpUtil.POST(task.getJobName());
				json = HttpUtilX.post(task.getJobName(), new HashMap<String,Object>());
			}
			
			System.out.println(format.format(new Date()) + " : 任务 ------> : " + task.getJobName() + "执行结果: ---> " + json);
			
			if(null != json && json.length() > 0){
				if(QuartzUtil.isJsonFormat(json)){
					JSONObject myjson = JSONObject.fromObject(json);
					if(myjson != null && myjson.containsKey("success")){
						boolean isSuccess = myjson.getBoolean("success");
						if(!isSuccess){
							str = myjson.containsKey("errorMsg") ? myjson.getString("errorMsg") : "";
							db.writeLog(format.format(new Date()), task.getJobName(), "http:" + param[0], str, 0);
							
						}
					}
					
					if(myjson != null && myjson.containsKey("result")){
						boolean isSuccess = myjson.getBoolean("result");
						if(!isSuccess){
							str =  myjson.containsKey("message") ? myjson.getString("message") :"";
							db.writeLog(format.format(new Date()), task.getJobName(), "http:" + param[0], str, 0);
						}
					}	
				}
			}
			
		} catch (Exception e) {
			try {
				e.printStackTrace();
				String msg = e.getMessage();
				if (msg != null && msg.length() > 1500) {
					msg.substring(0, 1500);
				}
				db.writeLog(format.format(new Date()), task.getJobName(), "http", msg==null?"null":msg, 0);
			} catch (Exception se) {
				se.printStackTrace();
			}
		}
	}
}